package xjutils

import (
	"bytes"
	"io/ioutil"
	"net/http"
)

func HttpGetStr(url string) (string, error) {
	resp, err := http.Get(url)
	if err != nil {
		return "", err
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	//fmt.Println(string(body))
	return string(body), nil
}

func HttpGetStrWithToken(url, token string) string {
	client := &http.Client{}
	reqest, err := http.NewRequest("GET", url, nil)
	reqest.Header.Add("Authorization", "Bearer "+token)
	if err != nil {
		panic(err)
	}
	//处理返回结果
	response, _ := client.Do(reqest)
	defer response.Body.Close()

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		// handle error
	}
	//fmt.Println(string(body))
	return string(body)
}

func HttpGetStrWithTokenInner(url, token string) (string, error) {
	client := &http.Client{}
	request, err := http.NewRequest("GET", url, nil)
	if err != nil || request == nil {
		return "", err
	}
	request.Header.Add("Authorization", "Bearer "+token)
	request.Header.Add("from", "Y")

	//处理返回结果
	response, err := client.Do(request)
	if err != nil || request == nil {
		return "", err
	}
	defer response.Body.Close()

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return "", err
	}
	return string(body), nil
}

func HttpPostStrWithTokenJson(url, token, json string) (string, error) {
	client := &http.Client{}
	var jsonStr = []byte(json)
	reqest, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
	reqest.Header.Add("Authorization", "Bearer "+token)
	reqest.Header.Set("Content-Type", "application/json")
	if err != nil {
		return "", err
	}
	//处理返回结果
	response, _ := client.Do(reqest)
	defer response.Body.Close()

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return "", err
	}
	//fmt.Println(string(body))
	return string(body), err
}

func HttpPostStrJson(url, json string) (string, error) {
	client := &http.Client{}
	var jsonStr = []byte(json)
	reqest, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
	reqest.Header.Set("Content-Type", "application/json")
	if err != nil {
		return "", err
	}
	//处理返回结果
	response, _ := client.Do(reqest)
	defer response.Body.Close()

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return "", err
	}
	//fmt.Println(string(body))
	return string(body), err
}

func HttpPostStrWithToken(url, token string) string {
	client := &http.Client{}
	reqest, err := http.NewRequest("POST", url, nil)
	reqest.Header.Add("Authorization", "Bearer "+token)
	if err != nil {
		panic(err)
	}
	//处理返回结果
	response, _ := client.Do(reqest)
	defer response.Body.Close()

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		// handle error
	}
	//fmt.Println(string(body))
	return string(body)
}
